package com.multi.framework.interceptor;

import com.multi.common.constant.CacheConstants;
import com.multi.common.constant.SourceConstant;
import com.multi.common.core.redis.RedisCache;
import com.multi.publicly.domain.WxUserInfo;
import com.multi.publicly.service.WxUserInfoService;
import com.multi.tenant.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Description 小程序端拦截器
 * @ClassName APPJwtAuthenticationTokenInterceptor
 * @Author pzj
 * @Data 2024/12/3 16:28
 */
@Component
public class APPJwtAuthenticationTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WxUserInfoService wxUserInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //通过token获取用户信息
        WxUserInfo wxUserInfo = tokenUtils.getWxUserInfo(request);
        //如果用户为空从数据库中查询用户信息
        if(wxUserInfo==null){
            wxUserInfo = wxUserInfoService.selectByUserId(wxUserInfo.getId());
            //将用户信息重新存储redis中
            redisCache.setCacheObject(CacheConstants.WX_USER_INFO + wxUserInfo.getId(),
                    wxUserInfo, 7, TimeUnit.DAYS);
        }
        String tenantId = tokenUtils.getTenantId(request);
        //设置租户信息
        request.setAttribute(SourceConstant.TENANT_ID,tenantId);
        //设置用户信息
        request.setAttribute(SourceConstant.USER_ID,wxUserInfo.getId());
        //设置用户openID
        request.setAttribute(SourceConstant.OPEN_ID,wxUserInfo.getOpenId());
        return true;
    }

}
